var express = require('express');
var router = express.Router();

const puppeteer = require('puppeteer')

router.get('/news', async (req, res) => {
    let inNewsList = await startBrowser()
    let nationalNewsList = await startBrowser2()
    res.send({
        inNewsList,
        nationalNewsList
    })
})

const urllsit = ['https://news.sina.com.cn/china/', 'https://world.huanqiu.com/']

async function startBrowser() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://news.sina.com.cn/china/');

    // 实现点击"娱乐"分类
    // await page.click('.navigation-7Gukt5kS');
    // await page.click('.index_viewMoreLink_qP-Dw')
    // 实现滚动加载更多新闻
    await page.evaluate(() => {
        window.scrollTo(0, document.body.scrollHeight);
    });

    const inNewsList = await page.evaluate(() => {
        const newsNodes = document.querySelectorAll('.feed-card-content .feed-card-item ');
        console.log(newsNodes, 'node双大蛇')
        const news = [];
        for (let node of newsNodes) {
            const title = node.querySelector('h2 a').textContent;
            const href = node.querySelector('h2 a').href;
            // const imgSrc = node.querySelector('img').src;
            news.push({title, href,});
        }
        return news;
    });

    // console.log(inNewsList);

    await browser.close();
    return inNewsList
}

async function startBrowser2() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('http://www.haiwainet.cn/');

    // 实现点击"娱乐"分类
    // await page.click('.navigation-7Gukt5kS');
    // await page.click('.index_viewMoreLink_qP-Dw')
    // 实现滚动加载更多新闻
    await page.evaluate(() => {
        window.scrollTo(0, document.body.scrollHeight);
    });

    const inNewsList = await page.evaluate(() => {
        const newsNodes = document.querySelectorAll('#yaowen  .onePic');
        const news = [];
        for (let node of newsNodes) {
            const title = node.querySelector('h4 a').textContent;
            // const title = node.getAttribute('data-share')
            const href = node.querySelector('h4 a').href;
            // const href = node.getAttribute('data-share').
            // const imgSrc = node.querySelector('img').src;
            news.push({href, title});
        }
        return news;
    });

    // console.log(inNewsList, '77');

    await browser.close();
    return inNewsList
}

//
// startBrowser().then(r => {
//     console.log('4515')
//     startBrowser2().then(res => {
//         console.log('c成功浮点数')
//     })
// })

module.exports = router
